package org.realogic.cfm.util;

import java.sql.Date;
import java.sql.Time;
import java.sql.Timestamp;
import java.util.Enumeration;
import java.util.HashMap;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.ConvertUtils;

public final class UtilRequest {

	static {
		ConvertUtils.register(new SqlDateConverter(), Date.class);
		ConvertUtils.register(new SqlTimeConverter(), Time.class);
		ConvertUtils.register(new SqlTimestampConverter(), Timestamp.class);
	}

	public static boolean populate(Object bean, HttpServletRequest request) throws ServletException {
		return populate(bean, null, null, request);
	}

	public static boolean populate(Object bean, String prefix, String suffix, HttpServletRequest request) {
		HashMap<String, String[]> properties = new HashMap<String, String[]>();
		Enumeration<?> names = request.getParameterNames();
		while (names.hasMoreElements()) {
			String name = (String) names.nextElement();
			String stripped = name;
			if (prefix != null) {
				if (!stripped.startsWith(prefix)) {
					continue;
				}
				stripped = stripped.substring(prefix.length());
			}
			if (suffix != null) {
				if (!stripped.endsWith(suffix)) {
					continue;
				}
				stripped = stripped.substring(0, stripped.length() - suffix.length());
			}
			properties.put(stripped, request.getParameterValues(name));
		}

		try {
			BeanUtils.populate(bean, properties);
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
		return true;
	}
}
